package com.eptok.gw.szcups.cups.message;

import java.io.ByteArrayOutputStream;
import java.util.Map;

import ys8583.parse.Conf8583;
import ys8583.parse.IOMessage;
import ys8583.po.Field;
import ys8583.po.MessageConf;

import com.eptok.gw.szcups.common.GateWayConstant;
import com.eptok.gw.szcups.common.KeyContainer;
import com.eptok.gw.szcups.hsm.HsmService;
import com.eptok.gw.szcups.util.StringUtils;
import com.solab.iso8583.common.ByteUtil;

/**
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-12 下午07:57:20
 */
public class MacGenerator {
	
	private final static String  MAC_GENERATE_SPLIT = " ";
	
	private final static String  Field_FORMAT_TYPE_LLVAR = "LLVAR";
	private final static String  Field_FORMAT_TYPE_LLLVAR = "LLLVAR";
	
	/**
	 * 生成渠道mac校验值
	 * @param ioMessage
	 * @throws Exception 
	 */
	public String generateChanMac(IOMessage ioMessage) throws Exception{
		ioMessage.removeField(128);
		
		//保存拼装mac要素的Fild地址(报文类型和90域特别处理)
		int[] macField = {2, 3, 4, 7, 11, 18, 25, 32, 33, 38, 39, 41, 42, 90};
		
		//获取模板map
		Conf8583 cf = (Conf8583) MessageConf.getInstance().getMap().get(GateWayConstant.MSG_CODE_TEMPLATE_ID);
		Map templateMap = cf.getTemplateMap();
		
		//先存入报文类型
		StringBuilder macBlock = new StringBuilder();
		macBlock.append(ioMessage.getRspMessageID());
		macBlock.append(MAC_GENERATE_SPLIT);
		
		String thisFieldValue;
		Object temObj;
		Field field; 
		for(int i=0; i<14; i++){
			temObj = ioMessage.getRspField(macField[i]);
			if(temObj != null){
				thisFieldValue = (String)temObj;
				
				//小写字母转化为大写字母
				thisFieldValue = thisFieldValue.trim().toUpperCase();
				//去空格及特殊字符
				thisFieldValue =StringUtils.processStr(thisFieldValue);
				
				if ((90 == macField[i]) && (20 < thisFieldValue.length())) {
					thisFieldValue = thisFieldValue.substring(0, 20);
		        }
				
				field = (Field) templateMap.get(String.valueOf(macField[i]));
				if(Field_FORMAT_TYPE_LLVAR.equals(field.getFormat())){			//LLVAR
					macBlock.append(String.format("%02d", thisFieldValue.length()));
				}else if(Field_FORMAT_TYPE_LLLVAR.equals(field.getFormat())){	//LLLVAR
					macBlock.append(String.format("%03d", thisFieldValue.length()));
				}
				macBlock.append(thisFieldValue);
				macBlock.append(MAC_GENERATE_SPLIT);
			}
		}
		
		String block = macBlock.toString();
		//去掉最后一位空格
		block = block.substring(0,block.length()-1);
		String temp = new HsmService().getMac(KeyContainer.getInstance().getChanZAK(), block.getBytes(GateWayConstant.CHAR_ENCODE));
		String mac_hex = ByteUtil.BinaryToHexString(temp.getBytes(GateWayConstant.CHAR_ENCODE)).substring(0,16);
		ioMessage.setRspField(128, ByteUtil.hexStringToBytes(mac_hex));
		
		return mac_hex;
	}
	
	
	  public static byte[] str2bcdOne(String s)
	  {
	    if (s.length() % 2 != 0)
	    {
	      s = s + "0";
	    }
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    char[] cs = s.toCharArray();
	    int high = 0;
	    int low = 0;
	    for (int i = 0; i < cs.length; i += 2) {
	      if ((cs[i] >= '0') && (cs[i] <= '9'))
	        high = cs[i] - '0';
	      else {
	        high = cs[i] - '0' - 7;
	      }

	      if ((cs[(i + 1)] >= '0') && (cs[(i + 1)] <= '9'))
	        low = cs[(i + 1)] - '0';
	      else {
	        low = cs[(i + 1)] - '0' - 7;
	      }
	      baos.write(high << 4 | low);
	    }
	    return baos.toByteArray();
	  }

	
	
	
//	/**
//	 * 生成渠道mac校验值
//	 * @param ioMessage
//	 * @throws Exception 
//	 */
//	public String testGenerateChanMac(IOMessage ioMessage) throws Exception{
//		//保存拼装mac要素的Fild地址(报文类型和90域特别处理)
//		int[] macField = {2, 3, 4, 7, 11, 18, 25, 32, 33, 38, 39, 41, 42, 90};
//		
//		//获取模板map
//		Conf8583 cf = (Conf8583) MessageConf.getInstance().getMap().get(GateWayConstant.MSG_CODE_TEMPLATE_ID);
//		Map templateMap = cf.getTemplateMap();
//		
//		//先存入报文类型
//		StringBuilder macBlock = new StringBuilder();
//		macBlock.append("0100");
//		macBlock.append(MAC_GENERATE_SPLIT);
//		
//		for(int i=0; i<14; i++){
//			String thisFieldValue = (String)ioMessage.getReqMesField(macField[i]);
//			Field field; 
//			if(thisFieldValue != null){
//				//小写字母转化为大写字母
//				thisFieldValue = thisFieldValue.trim().toUpperCase();
//				thisFieldValue =StringUtils.processStr(thisFieldValue);
//				
//				if ((90 == macField[i]) && (20 < thisFieldValue.length())) {
//					thisFieldValue = thisFieldValue.substring(0, 20);
//		        }
//				
//				field = (Field) templateMap.get(String.valueOf(macField[i]));
//				if(Field_FORMAT_TYPE_LLVAR.equals(field.getFormat())){			//LLVAR
//					macBlock.append(String.format("%02d", thisFieldValue.length()));
//				}else if(Field_FORMAT_TYPE_LLLVAR.equals(field.getFormat())){	//LLLVAR
//					macBlock.append(String.format("%03d", thisFieldValue.length()));
//				}
//				macBlock.append(MAC_GENERATE_SPLIT);
//				macBlock.append(thisFieldValue);
//			}
//		}
//		
//		String block = macBlock.toString();
//		
//		System.out.println(">>>>>>>>>>>>>>>>>>>>mac_block:" + block);
//		System.out.println(">>>>>>>>>>>>>>>>>>>>zak:" + KeyContainer.getInstance().getChanZAK());
//		String mac_hex = new HsmService().getMac(KeyContainer.getInstance().getChanZAK(), block.getBytes(GateWayConstant.CHAR_ENCODE));
//		System.out.println(">>>>>>>>>>>>>>>>>>>>the mac is:" + mac_hex);
//		ioMessage.setRspField(128, ByteUtil.hexStringToBytes(mac_hex));
//		
//		return mac_hex;
//	}
	
	/**
	 * 生成商户连接的MAC
	 * @param ioMessage
	 * @param mak
	 * @return
	 * @throws Exception
	 */
	public String generateMarchantMac(IOMessage ioMessage,String mak) throws Exception{
		ioMessage.setRspField(128, new byte[8]);
		byte[] temp = ioMessage.createResponseMsg();
		byte[] block = new byte[temp.length-8];
		System.arraycopy(temp, 0, block, 0, block.length);
		String mac_hex = new HsmService().getMac(mak, block);
		ioMessage.setRspField(128, ByteUtil.hexStringToBytes(mac_hex));
		return mac_hex;
	}
	
}
